package com.wiiss.common.controller;

import com.wiiss.common.config.WiissConfig;
import com.wiiss.common.constant.Constants;
import com.wiiss.common.domain.AjaxResult;
import com.wiiss.common.domain.AttachmentTask;
import com.wiiss.common.domain.page.TableDataInfo;
import com.wiiss.common.mapper.AttachmentTaskMapper;
import com.wiiss.common.utils.StringUtils;
import com.wiiss.common.utils.file.FileUploadUtils;
import com.wiiss.common.utils.file.FileUtils;
import com.wiiss.framework.config.ServerConfig;
import com.wiiss.framework.web.domain.Server;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 通用请求处理
 *
 * @author my
 */
@Api(tags = "通用请求处理")
@RestController
public class CommonController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Value("${maven.packageTime:}")
    private String packageTime;

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private AttachmentTaskMapper attachmentTaskMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @ApiOperation("通用下载请求")
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = WiissConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @ApiOperation("通用上传请求")
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = WiissConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @ApiOperation("本地资源通用下载")
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = WiissConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 查询附件任务
     */
    @ApiOperation("查询附件任务")
    @GetMapping("/common/attachment/task")
    public TableDataInfo attachmentTasks(AttachmentTask task) {
        startPage();
        List<AttachmentTask> list = attachmentTaskMapper.select(task);
        return getDataTable(list);
    }

    @ApiOperation("获取jar的版本号")
    @RequestMapping("/mcs/version/getVersion")
    public String getVersion() throws Exception {
        // 获取到的packageTime是utc时间，需要转换成北京时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date utcTime = sdf.parse(packageTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(utcTime);
        // 转换成北京时间需要+8小时
        calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String bjTime = simpleDateFormat.format(calendar.getTime());
        return "5.1_" + bjTime.substring(2);//"5.1_221206"
    }

    @ApiOperation("服务器监控")
    @PreAuthorize("@ss.hasPermi('monitor:server:list')")
    @GetMapping("/monitor/server")
    public AjaxResult getServerInfo() throws Exception {
        Server server = new Server();
        server.copyTo();
        return AjaxResult.success(server);
    }

    @ApiOperation("获取redis服务信息")
    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @GetMapping("/monitor/cache")
    public AjaxResult getRedisInfo() {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::info);
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::dbSize);

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        assert commandStats != null;
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return AjaxResult.success(result);
    }
}
